<!--
  * 下拉滚动加载选择框
  *
  * @Author:    zhoujk
  * @Date:      2025-01-25 15:25
-->
<template>
  <a-select
    v-model:value="selectValue"
    :style="`width: ${width}`"
    :placeholder="props.placeholder"
    :showSearch="true"
    :allowClear="true"
    :filter-option="false"
    :size="size"
    @search="handleSearch"
    @dropdownVisibleChange="handleDropdownVisibleChange"
    @popupScroll="handlePopupScroll"
    @change="onChange"
    @deselect="onDeselect"
    :loading="loading"
  >
    <a-select-option v-for="item in dataList" :key="item.id" :value="item.id">
      {{ item.companyName }}
    </a-select-option>

    <template v-if="loading" #notFoundContent>
      <a-spin size="small" />
    </template>
  </a-select>
</template>

<script setup>
  import { onMounted, ref, watch, reactive } from 'vue'
  import { agentApi } from '/src/api/business/b-agent/agent/agent-api.js'
  import { smartSentry } from '/src/lib/smart-sentry'
  import { debounce } from 'lodash-es'

  // =========== 属性定义 和 事件方法暴露 =============

  const props = defineProps({
    value: [Number, Array],
    placeholder: {
      type: String,
      default: '请选择',
    },
    width: {
      type: String,
      default: '100%',
    },
    size: {
      type: String,
      default: 'default',
    },
    pageSize: {
      type: Number,
      default: 10,
    },
    // 禁用标识
    status: {
      type: Number,
      default: 1,
    },
  })

  const emit = defineEmits(['update:value', 'change'])

  const loading = ref(false)
  const searchKeyword = ref('')
  const hasMore = ref(true)

  const pagination = reactive({
    current: 1,
    pageSize: props.pageSize,
    total: 0,
  })

  // =========== 查询数据 =============

  //员工列表数据
  const dataList = ref([])
  const selectValue = ref(props.value)

  async function query() {
    if (loading.value || !hasMore.value) return

    loading.value = true
    try {
      let params = {
        companyNameLeftLike: searchKeyword.value,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
      }
      if (null != props.status) {
        params.status = props.status
      }
      let res = await agentApi.page(params)

      dataList.value = [...dataList.value, ...res.data]
      pagination.total = res.total
      hasMore.value = dataList.value.length < pagination.total
      pagination.current++
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      loading.value = false
    }
  }

  // 防抖搜索函数
  const handleSearch = debounce((value) => {
    searchKeyword.value = value
    hasMore.value = true
    dataList.value = [] // 清空旧数据
    pagination.current = 1
    query()
  }, 500)

  // 下拉框展开时加载数据
  const handleDropdownVisibleChange = (open) => {
    if (open) {
      query()
    }
  }

  // 修改后的滚动处理函数
  const handlePopupScroll = debounce(async (e) => {
    const { scrollTop, scrollHeight, clientHeight } = e.target
    const isNearBottom = scrollHeight - scrollTop <= clientHeight + 20

    if (isNearBottom && hasMore.value && !loading.value) {
      await query()
    }
  }, 200)

  // =========== 选择 监听、事件 =============

  // 监听value变化
  watch(
    () => props.value,
    (newVal) => {
      selectValue.value = newVal
    },
  )

  function onChange(value) {
    emit('update:value', value)
    emit('change', value)
  }

  function onDeselect() {
    searchKeyword.value = ''
    hasMore.value = true
    dataList.value = [] // 清空旧数据
    pagination.current = 1
  }

  onMounted(query)
</script>
